package com.wmada.toolkit.common.bean;

import com.alibaba.fastjson.JSON;
import com.wmada.toolkit.common.TypeUtils;
import org.apache.commons.lang3.StringUtils;

/**
 * @author will.ma
 * @date 16/6/18
 */
@SuppressWarnings({"unused", "UnusedReturnValue"})
public class ActionResult<T> {

    private T       data;
    private String  message  = "";
    private boolean success  = true;
    private long    timeCost = 0;

    public ActionResult() {
    }

    public ActionResult(T data) {
        success(data);
    }

    public ActionResult(String message, boolean success) {
        if (success) {
            success(null, message);
        } else {
            failure(message);
        }
    }

    public ActionResult(T data, String message, boolean success) {
        if (success) {
            success(data, message);
        } else {
            failure(data, message);
        }
    }

    public String getMessage() {
        return message;
    }

    public T getData() {
        return data;
    }

    public boolean isSuccess() {
        return success;
    }

    public boolean isFailure() {
        return !success;
    }

    public boolean isOk() {
        return success;
    }

    public long getTimeCost() {
        return timeCost;
    }

    public void setTimeCost(long timeCost) {
        this.timeCost = timeCost;
    }

    public ActionResult<T> failure(String message) {
        this.data = null;
        this.success = false;
        this.message = message;
        return this;
    }

    public ActionResult<T> failure(T data, String message) {
        this.data = data;
        this.success = false;
        this.message = message;
        return this;
    }

    public ActionResult<T> success(T data) {
        this.data = data;
        this.success = true;
        this.message = "";
        return this;
    }

    public ActionResult<T> success(T data, String message) {
        this.data = data;
        this.success = true;
        this.message = message;
        return this;
    }

    public ActionResult<T> update(ActionResult<T> status) {
        data = status.data;
        success = success && status.success;
        message = (StringUtils.isNotBlank(message) ? message + "\n" : "") + status.message;
        return this;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder("=============== ");
        sb.append(isSuccess() ? "Success" : "Failure").append(" Action Result ===============\n");
        sb.append("Message: ").append(message).append('\n');
        if (data == null) {
            sb.append("Data: null\n");
        } else if (TypeUtils.isBasic(data.getClass())) {
            sb.append("Data: ").append(data).append('\n');
        } else {
            sb.append("Data: ").append(JSON.toJSONString(data)).append('\n');
        }
        sb.append("=====================================================");
        return sb.toString();
    }
}
